﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using ZJ.Finance.BusinessRule;
using ZJ.Finance.DataModel;


namespace Finance.Controllers
{
    public class DataController : Controller
    {
        /// <summary>
        /// 注册用户，
        /// </summary>
        /// <param name="userJson">用户对象的JSON数据</param>
        /// <returns>｛Error:1|-1，Data：Msg|ErrorMsg｝</returns>
        public string RegistUser(string userJson)
        {
            try
            {
                var user = JsonConvert.DeserializeObject<User>(userJson);

                if (user.LoginEmail == "")
                    return DataProvider.GetJosnp(DataProvider.RetrunData(-1, "您还没有输入登录 Email，请认真填写。"));

                var userfromServer = DataProvider.Instance.GetUser(user.LoginEmail);

                if (userfromServer != null)
                    return DataProvider.GetJosnp(DataProvider.RetrunData(-1, "登录 Email 已经被其它用户占有了，请重新填写。"));

                user.Password = DataProvider.GetMd5(user.Password);
                DataProvider.Instance.CreateUser(user);

                return DataProvider.GetJosnp(DataProvider.RetrunData(1, "恭喜您已加入 Finace！"));
            }
            catch (Exception ex)
            {
                return DataProvider.GetJosnp(DataProvider.RetrunData(-1, ex.ToString()));
            }
        }

        /// <summary>
        /// 用户登录到系统
        /// </summary>
        /// <param name="loginEmail">登录EMail</param>
        /// <param name="psw">密码</param>
        /// <returns>｛Error:1|-1，Data：User|""｝</returns>
        public string Login(string loginEmail, string psw)
        {
            loginEmail = loginEmail.SqlFilter();
            psw = psw.SqlFilter();

            List<User> users = DataProvider.Instance.GetUsers(string.Empty, string.Format("LoginEmail = '{0}'", loginEmail));
            if (users.Count <= 0)
            {
                return DataProvider.GetJosnp(DataProvider.RetrunData(-1, "您不是有效的用户，请注册成为有效用户后再登录。"));
            }

            User cuser = users[0];
            psw = FormsAuthentication.HashPasswordForStoringInConfigFile(psw, "MD5");

            if (cuser.Password.Equals(psw))
            {
                string userStr = JsonConvert.SerializeObject(cuser, new JavaScriptDateTimeConverter());
                FormsAuthentication.SetAuthCookie(userStr, false);
                return GetCurrentUser();
            }

            return DataProvider.GetJosnp(DataProvider.RetrunData(-1, "密码错误，请合对后重新输入。"));
        }

        /// <summary>
        /// 获取当前已登录的用户信息
        /// </summary>
        /// <returns>｛Error:1|-1，Data：User|""｝</returns>
        public string GetCurrentUser()
        {
            try
            {
                string cookieName = FormsAuthentication.FormsCookieName;

                HttpCookie authCookie = HttpContext.Request.Cookies[cookieName];
                if (authCookie == null)
                {
                    //FormsAuthentication.RedirectToLoginPage();
                    return DataProvider.GetJosnp(DataProvider.RetrunData(-1, ""));
                }
                FormsAuthenticationTicket tickey = FormsAuthentication.Decrypt(authCookie.Value);
                if (tickey != null)
                {
                    var userStr = tickey.Name;
                    //User user = JsonConvert.DeserializeObject<User>(userStr);
                    return DataProvider.GetJosnp(userStr);
                }
                return DataProvider.GetJosnp(DataProvider.RetrunData(-1, "用户还没有登录或用户登录过期。"));
            }
            catch (Exception ex)
            {
                //FormsAuthentication.RedirectToLoginPage();
                return DataProvider.GetJosnp(DataProvider.RetrunData(-1, ex.ToString()));
            }
        }

        public string CreateBill(int billOperationId, string billCategory, decimal money, int projectId, int accountId, string description)
        {
            Dictionary<string, object> datas = new Dictionary<string, object>();
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    User currentUser = DataProvider.GetCurrentUser();
                    billCategory = billCategory.SqlFilter();
                    description = description.SqlFilter();

                    string billCategoryWhere = string.Format("Name='{0}' and LoginEmail='{1}' and BillOperationId={2}",
                        billCategory, currentUser.LoginEmail, billOperationId);

                    List<BillCategory> categories = DataProvider.Instance.GetBillCategories(string.Empty, billCategoryWhere);
                    BillCategory newCategory = null;
                    bool isnewCategory = false;
                    if (categories.Count <= 0)
                    {
                        newCategory = new BillCategory();
                        newCategory.BillOperationId = billOperationId;
                        newCategory.LoginEmail = currentUser.LoginEmail;
                        newCategory.CDate = DateTime.Now;
                        newCategory.Name = billCategory;
                        newCategory.BillCategoryId = DataProvider.Instance.CreateBillCategory(newCategory);
                        isnewCategory = true;
                    }
                    else
                    {
                        newCategory = categories[0];
                    }

                    Bill bill = new Bill();
                    bill.AccountId = accountId;
                    bill.BillCategoryId = newCategory.BillCategoryId;
                    bill.BillOperationId = billOperationId;
                    bill.CDateTime = DateTime.Now;
                    bill.CDate = bill.CDateTime;
                    bill.Description = description;
                    bill.LoginEmail = currentUser.LoginEmail;
                    bill.Money = money;
                    bill.ProjectId = projectId;
                    int id = DataProvider.Instance.CreateBill(bill);
                    bill.BillId = id;

                    datas.Add("Error", false);
                    datas.Add("IsNewCateory", isnewCategory);
                    datas.Add("Bill", bill);
                    datas.Add("Category", newCategory);
                    scope.Complete();
                }
            }
            catch (Exception ex)
            {
                datas.Add("Error", false);
                datas.Add("ErrorMsg", ex.ToString());
            }

            //datas.Add("ErrorMsg", "");
            return DataProvider.GetJosnp(JsonConvert.SerializeObject(datas, new JavaScriptDateTimeConverter()));

            //return DataProvider.GetJosnp(DataProvider.RetrunData(1, bill));
        }

        public string CreateTransferBill(decimal money, int outAccount, int inAccount)
        {
            Dictionary<string, object> datas = new Dictionary<string, object>();
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    User currentUser = DataProvider.GetCurrentUser();
                    Bill outBill = new Bill();
                    outBill.LoginEmail = currentUser.LoginEmail;
                    outBill.AccountId = outAccount;
                    outBill.BillOperationId = 3;
                    outBill.BillCategoryId = 28;
                    outBill.Money = money;
                    outBill.ProjectId = 7;
                    outBill.CDateTime = DateTime.Now;
                    outBill.CDate = outBill.CDateTime;
                    outBill.Description = string.Empty;
                    outBill.BillId = DataProvider.Instance.CreateBill(outBill);

                    Bill inBill = new Bill();
                    inBill.LoginEmail = currentUser.LoginEmail;
                    inBill.AccountId = inAccount;
                    inBill.BillOperationId = 4;
                    inBill.BillCategoryId = 25;
                    inBill.Money = money;
                    inBill.ProjectId = 7;
                    inBill.CDateTime = DateTime.Now;
                    inBill.CDate = outBill.CDateTime;
                    inBill.Description = string.Empty;
                    inBill.BillId = DataProvider.Instance.CreateBill(inBill);
                    scope.Complete();
                    datas.Add("Error", false);
                    datas.Add("OutBill", outBill);
                    datas.Add("InBill", inBill);
                }

            }
            catch (Exception ex)
            {
                datas.Add("Error", false);
                datas.Add("ErrorMsg", ex.ToString());
            }

            return DataProvider.GetJosnp(JsonConvert.SerializeObject(datas, new JavaScriptDateTimeConverter()));
        }

        public string GetBillDetails(int year, int month, string operations, string projects, string accounts)
        {
            try
            {
                User currentUser = DataProvider.GetCurrentUser();
                int total = 0;
                string order = "CDateTime DESC";
                DateTime startdate = new DateTime(year, month, 1);
                DateTime enddate = startdate.AddDays(DateTime.DaysInMonth(year, month));
                string dateWhere = string.Format("CDate>='{0}' and  CDate <'{1}'", startdate, enddate);
                string operationsWhere = string.Empty;
                if (operations != string.Empty)
                {
                    operationsWhere = string.Format("and BillOperationId in ({0})", operations);
                }
                string accountsWhere = string.Empty;
                if (accounts != string.Empty)
                {
                    accountsWhere = string.Format("and AccountId in ({0})", accounts);
                }
                string projectsWhere = string.Empty;
                if (projects != string.Empty)
                {
                    projectsWhere = string.Format("and ProjectId in ({0})", projects);
                }
                string where = string.Format("LoginEmail='{0}' and ({1}) {2} {3} {4}",
                    currentUser.LoginEmail, dateWhere, operationsWhere, accountsWhere, projectsWhere);
                List<VBillDetail> billDetails = DataProvider.Instance.GetVBillDetails(order, where);
                return DataProvider.GetJosnp(DataProvider.RetrunData(total, billDetails));
            }
            catch (Exception ex)
            {
                return DataProvider.GetJosnp(DataProvider.RetrunData(-1, ex.ToString()));
            }


        }

        public string GetBillDetails2(string jsonWhere)
        {
            //pageIndex: currentPage + 1,
            //pageSize: psplitter.PageSize,
            //year: yearEdit.GetSelect().Value,
            //month: MonthList.GetSelect()[0].data.Value

            //var user = JsonConvert.DeserializeObject(jsonWhere) as JObject;;

            var where = JsonConvert.DeserializeAnonymousType(jsonWhere, 
                new { PageIndex = 0, PageSize = 0, Year = 2010, Month = 1 });
            int a = where.PageIndex;
          
            return DataProvider.GetJosnp("");
        }

    }
}
